package com.shenhaofeng.app.component;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;

import com.trello.rxlifecycle.LifecycleProvider;
import com.trello.rxlifecycle.LifecycleTransformer;
import com.trello.rxlifecycle.RxLifecycle;

import javax.annotation.Nonnull;

import rx.Observable;
import rx.subjects.BehaviorSubject;


/**
 * Created by Administrator on 2016/9/20.
 */
public class BaseService extends Service  implements LifecycleProvider<ServiceEvent> {


    private final BehaviorSubject<ServiceEvent> lifecycleSubject = BehaviorSubject.create();

    @Override
    public void onCreate() {
        super.onCreate();
        lifecycleSubject.onNext(ServiceEvent.CREATE);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        lifecycleSubject.onNext(ServiceEvent.BIND);
        return null;
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        lifecycleSubject.onNext(ServiceEvent.DESTROY);
    }


    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
        lifecycleSubject.onNext(ServiceEvent.START);
    }


    @Override
    public boolean onUnbind(Intent intent) {
        lifecycleSubject.onNext(ServiceEvent.UNBIND);
        return super.onUnbind(intent);
    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        lifecycleSubject.onNext(ServiceEvent.STARTCOMMAND);
        return super.onStartCommand(intent, flags, startId);
    }


    @Override
    public void onRebind(Intent intent) {
        super.onRebind(intent);
        lifecycleSubject.onNext(ServiceEvent.REBIND);
    }



    @Nonnull
    @Override
    public Observable<ServiceEvent> lifecycle() {
        return lifecycleSubject.asObservable();
    }


    @Nonnull
    @Override
    public <T> LifecycleTransformer<T> bindUntilEvent(@Nonnull ServiceEvent event) {
        return RxLifecycle.bindUntilEvent(lifecycleSubject, event);
    }


    @Nonnull
    @Override
    public <T> LifecycleTransformer<T> bindToLifecycle() {
        throw new UnsupportedOperationException();
    }
}
